package com.ming.utils;

import java.text.DecimalFormat;

/**
 * author : changer
 * date   : 2020/8/12
 * desc   :
 * // TODO: 2020/8/12 字符串转数字等 以及格式化  格式化价格
 */
public final class NumberHelper {


    private NumberHelper(){
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * String -> int
     * @param number
     * @return
     */
    public static int stringToInt(String number){
        if (StringHelper.isEmpty(number)){
            return 0;
        }
        try {
            return Integer.valueOf(number);
        }catch (NumberFormatException e){
            return 0;
        }
    }

    /**
     * String -> long
     * @param number
     * @return
     */
    public static long stringToLong(String number){
        if (StringHelper.isEmpty(number)){
            return 0L;
        }
        try {
            return Long.valueOf(number);
        }catch (NumberFormatException e){
            return 0L;
        }

    }

    /**
     * String -> float
     * @param number
     * @return
     */
    public static float stringToFloat(String number){
        if (StringHelper.isEmpty(number)){
            return 0f;
        }
        try {
            return Float.valueOf(number);
        }catch (NumberFormatException e){
            return 0f;
        }
    }

    /**
     * String -> double
     * @param number
     * @return
     */
    public static double stringToDouble(String number){

        if (StringHelper.isEmpty(number)){
            return 0d;
        }
        try {
            return Double.valueOf(number);
        }catch (NumberFormatException e){
            return 0d;
        }

    }


    /**
     *
     * @param number
     * @return
     */
    public static String format2Decimals(double number){
        try {
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            String formatResult = decimalFormat.format(number);
            if (formatResult.startsWith(".")) {
                return "0" + formatResult;
            } else {
                return formatResult;
            }
        }catch (Exception e){
            return "";
        }
    }

    //TODO String -> 格式化double
    public static String format2Decimals(String number){
        try {
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            String formatResult = decimalFormat.format(stringToDouble(number));
            if (formatResult.startsWith(".")) {
                return "0" + formatResult;
            } else {
                return formatResult;
            }
        }catch (Exception e){
            return "";
        }
    }



}
